package com.woniu.write;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MultiThreadFileWriter {

    private File file;
    private FileWriter fileWriter;
    private Lock lock;

    public MultiThreadFileWriter(String filePath) throws IOException {
        this.file = new File(filePath);
        if (!file.exists()) {
            file.createNewFile();
        }
        this.fileWriter = new FileWriter(file, true); // 追加写入
        this.lock = new ReentrantLock();
    }

    public void write(String content) {
        lock.lock();
        try {
            fileWriter.write(content);
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void close() {
        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        MultiThreadFileWriter writer = new MultiThreadFileWriter("test.txt");
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                writer.write("Thread 1: " + i + "\n");
            }
        });
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                writer.write("Thread 2: " + i + "\n");
            }
        });
        thread1.start();
        thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        writer.close();
    }
}
